package com.cloud.code.线程池.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 描述:
 * 线程池
 *
 * @author 54485
 * @create 2018-09-17 16:53
 */
public class ExecutorsTest {

    public static class Dog implements Runnable{


        @Override
        public void run() {
            System.out.println("jiao--------"+Thread.currentThread().getName());

        }
    }

    public static int i = 100;

    public static void main(String[] args) {

        //可定长度的线程池
        ExecutorService pool = Executors.newFixedThreadPool(5);

        for (int i= 0;i<50;i++)
        pool.execute(new Thread(new Dog(),"thread:"+i));
        pool.shutdown();
        pool.shutdown();

        //可缓存的线程池，重复利用
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

        for (int j = 0; j < 100; j++) {
            int temp = j;
            cachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"i="+temp);
                }
            });
        }
        cachedThreadPool.shutdown();

        //可定时的线程池
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
        for (int j = 0; j < 20; j++) {
            scheduledThreadPool.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            },3, TimeUnit.SECONDS);
        }
        scheduledThreadPool.shutdown();


        //单线程
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        for (int j = 0; j < 10; j++) {
            singleThreadExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }
    }
}
